import ssl
import pywbem

# **SMI-S 服务器信息**
SMIS_HOST = "https://192.168.100.68:5989"
SMIS_USER = "OPS@admin"
SMIS_PASS = "OPS@2024ttl"
SMIS_NAMESPACE = "root/ibm"


# **状态码映射**
STATUS_CODES = {
    0: "Unknown",
    1: "Other",
    2: "OK",
    3: "Degraded",
    4: "Stressed",
    5: "Predictive Failure",
    6: "Error",
    7: "Non-Recoverable Error",
    8: "Starting",
    9: "Stopping",
    10: "Stopped",
}


def parse_status(status_list):
    """转换 OperationalStatus 数值为可读文本"""
    return [STATUS_CODES.get(status, f"Unknown({status})") for status in status_list]


def connect_smis():
    """建立 SMI-S 连接（修复 SSL 连接问题）"""
    try:
        conn = pywbem.WBEMConnection(
            SMIS_HOST,
            (SMIS_USER, SMIS_PASS),
            default_namespace=SMIS_NAMESPACE,
            timeout=30,
            no_verification=True,
        )
        print("成功连接到 SMI-S 服务器")
        return conn
    except Exception as e:
        print(f"SMI-S 连接失败: {e}")
        return None



def get_storage_system(conn):
    """获取存储系统状态"""
    try:
        instances = conn.EnumerateInstances("CIM_ComputerSystem", namespace=SMIS_NAMESPACE)
        for inst in instances:
            name = inst.get("ElementName", "Unknown")
            status = parse_status(inst.get("OperationalStatus", []))
            print(f"📦 存储系统: {name}, 状态: {status}")
    except Exception as e:
        print(f"⚠️ 获取存储系统信息失败: {e}")


def get_cpu_usage(conn):
    """获取 CPU 使用率"""
    try:
        instances = conn.EnumerateInstances("CIM_StorageProcessorStatisticalData", namespace=SMIS_NAMESPACE)
        for inst in instances:
            name = inst.get("InstanceID", "Unknown")
            usage = inst.get("PercentProcessorTime", 0)
            print(f"🖥️ CPU: {name}, 使用率: {usage:.2f}%")
    except Exception as e:
        print(f"⚠️ 获取 CPU 使用率失败: {e}")


def get_memory_usage(conn):
    """获取内存使用率"""
    try:
        instances = conn.EnumerateInstances("CIM_MemoryStatisticalData", namespace=SMIS_NAMESPACE)
        for inst in instances:
            total_mem = inst.get("TotalMemory", 1)
            available_mem = inst.get("AvailableMemory", 0)
            used_mem = total_mem - available_mem
            usage_percent = (used_mem / total_mem) * 100 if total_mem else 0
            print(
                f"💾 内存总量: {total_mem / 1024:.2f} GB, 已用: {used_mem / 1024:.2f} GB, 使用率: {usage_percent:.2f}%")
    except Exception as e:
        print(f"⚠️ 获取内存使用率失败: {e}")


def get_disk_info(conn):
    """获取磁盘状态"""
    try:
        instances = conn.EnumerateInstances("CIM_StorageExtent", namespace=SMIS_NAMESPACE)
        for inst in instances:
            name = inst.get("ElementName", "Unknown")
            size = inst.get("BlockSize", 1) * inst.get("NumberOfBlocks", 0) / (1024 ** 3)
            status = parse_status(inst.get("OperationalStatus", []))
            print(f"💽 硬盘: {name}, 容量: {size:.2f} GB, 状态: {status}")
    except Exception as e:
        print(f"⚠️ 获取硬盘信息失败: {e}")


def get_fan_info(conn):
    """获取风扇状态"""
    try:
        instances = conn.EnumerateInstances("CIM_Fan", namespace=SMIS_NAMESPACE)
        for inst in instances:
            name = inst.get("ElementName", "Unknown")
            speed = inst.get("DesiredSpeed", "Unknown")
            status = parse_status(inst.get("OperationalStatus", []))
            print(f"🌀 风扇: {name}, 转速: {speed} RPM, 状态: {status}")
    except Exception as e:
        print(f"⚠️ 获取风扇信息失败: {e}")


def get_power_info(conn):
    """获取电源状态"""
    try:
        instances = conn.EnumerateInstances("CIM_PowerSupply", namespace=SMIS_NAMESPACE)
        for inst in instances:
            name = inst.get("ElementName", "Unknown")
            status = parse_status(inst.get("OperationalStatus", []))
            print(f"🔋 电源: {name}, 状态: {status}")
    except Exception as e:
        print(f"⚠️ 获取电源信息失败: {e}")


def main():
    """主程序"""
    conn = connect_smis()
    if not conn:
        print("❌ 连接 SMI-S 服务器失败，终止监控")
        return

    print("\n🔍 **开始监控 IBM Storwize V7000**")
    get_storage_system(conn)
    get_cpu_usage(conn)
    get_memory_usage(conn)
    get_disk_info(conn)
    get_fan_info(conn)
    get_power_info(conn)
    print("\n✅ **监控完成**")


if __name__ == "__main__":
    main()